package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private DeptMapper deptMapper;

    @Transactional
    @Override
    public void saveEmpAndEmpExpr(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(v -> v.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    @Override
    public Result getPageResult(EmpQueryParam param) {
        if (Objects.isNull(param)) {
            throw new RuntimeException("参数不能为空");
        }
        String name = param.getName();
        Integer gender = param.getGender();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<Emp>()
                .like(StringUtils.isNotBlank(name), Emp::getName, name)
                .eq(ObjectUtils.isNotNull(gender), Emp::getGender, gender)
                .between(ObjectUtils.isNotNull(begin) && ObjectUtils.isNotNull(end), Emp::getEntryDate, begin, end);


        page = this.page(page, queryWrapper);
        List<Emp> empList = page.getRecords();
        Set<Integer> deptSet = empList.stream().map(emp -> emp.getDeptId()).collect(Collectors.toSet());
        List<Dept> deptList = deptMapper.selectList(Wrappers.<Dept>lambdaQuery().in(Dept::getId, deptSet));
        Map<Integer, String> deptMap = deptList.stream().collect(Collectors.toMap(dept -> dept.getId(), dept -> dept.getName()));
        empList.forEach(emp -> {emp.setDeptName(deptMap.get(emp.getDeptId()));});
        PageResult<Emp> pageResult = new PageResult<>(page.getTotal(), empList);
        return Result.success(pageResult);
    }

    @Override
    public Emp getEmpById(Integer id) {
        if (ObjectUtils.isNull(id)) {
            throw new RuntimeException("参数不能为空");
        }
        Emp emp = this.getById(id);
        emp.setExprList(empExprService.list(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id)));
        return emp;
    }

    @Override
    public void updateEmp(Emp emp) {
        if (ObjectUtils.isNull(emp)) {
            throw new RuntimeException("参数不能为空");
        }
        emp.setUpdateTime(LocalDateTime.now());
        // this.update(emp, Wrappers.<Emp>lambdaQuery().eq(Emp::getId, emp.getId()));
        this.updateById(emp);
        // empExprService.removeById(emp.getId());
        //错误，因为我要删除的工作经历的id不是，emp的id，而是工作经历的emp_id才是emp的id
        empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        List<EmpExpr> exprList = emp.getExprList();
        if (ObjectUtils.isNotNull(exprList)) {
            exprList.forEach(v -> {
                v.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public void removeEmpsByIds(List<Integer> ids) {
        if (ObjectUtils.isNull(ids)) {
            throw new RuntimeException();
        }
        this.removeBatchByIds(ids);
        // ids.forEach(id -> {
        //     empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id));
        // });还是不够方便，想想当初sql是怎么写的
        empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids));
    }
}
